package com.zqc.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zqc.common.R;
import com.zqc.entity.Category;
import com.zqc.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/category")
public class CategoryController {
    @Autowired
    public CategoryService categoryService;

    /**
     * 添加菜品分类
     *
     * @param category
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody Category category) {
        categoryService.save(category);
        return R.success("菜品分类保存成功");
    }

    /**
     * 分页查询
     *
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize) {
        // 创建分页构造器
        Page<Category> categoryPage = new Page<>(page, pageSize);
        // 查询数据
        categoryService.page(categoryPage, new LambdaQueryWrapper<Category>()
                .orderByAsc(Category::getSort));
        return R.success(categoryPage);
    }

    @PutMapping
    public R<String> update(@RequestBody Category category) {
        categoryService.updateById(category);
        return R.success("修改菜品成功");
    }

    @DeleteMapping
    public R<String> deleteById(Long id) {
        categoryService.remove(id);
        return R.success("菜品分类删除成功");
    }

    /**
     * 查询分类回显
     * @param category
     * @return
     */
    @GetMapping("/list")
    public R<List<Category>> list(Category category) {
        List<Category> categories = categoryService.list(new LambdaQueryWrapper<Category>()
                .eq(category.getType() != null, Category::getType, category.getType())
                .orderByAsc(Category::getSort)
                .orderByDesc(Category::getUpdateTime)
        );
        return R.success(categories);
    }
}
